package com.young4j.seckill.service.impl;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;

import com.young4j.seckill.dao.SeckillDao;
import com.young4j.seckill.dao.SuccessKilledDao;
import com.young4j.seckill.dto.Exposer;
import com.young4j.seckill.dto.SeckillExecution;
import com.young4j.seckill.entity.Seckill;
import com.young4j.seckill.exception.RepeatKillException;
import com.young4j.seckill.exception.SeckillCloseException;
import com.young4j.seckill.exception.SeckillException;
import com.young4j.seckill.service.SeckillService;

public class SeckillServiceImpl implements SeckillService {
	private Logger LOG = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private SeckillDao seckillDao;
	@Autowired
	private SuccessKilledDao successKilledDao;
	private final String SLAT = "FJDAOFUITjfiaond348f9jdfhiuiyrqh!@#$%%$#@!)(*&jdfiw";
	public List<Seckill> getSeckillList() {
		return seckillDao.queryAll(0, 100);
	}

	public Seckill getById(long seckillId) {
		return seckillDao.queryById(seckillId);
	}

	public Exposer exportSeckillUrl(long seckillId) {
		Seckill seckill = this.getById(seckillId);
		if(seckill == null){
			return new Exposer(false, seckillId);
		}
		Date startTime = seckill.getStartTime();
		Date endTime = seckill.getEndTime();
		Date nowTime = new Date();
		if(nowTime.getTime() > endTime.getTime() || nowTime.getTime() < startTime.getTime()){
			return new Exposer(false, seckillId,nowTime.getTime(),startTime.getTime(),endTime.getTime());
		}
		String md5 = getMD5(seckillId);
		return new Exposer(true,md5,seckillId);
	}

	public SeckillExecution executeSeckill(long seckillId, long userPhone,
			String md5) throws SeckillException, RepeatKillException,
			SeckillCloseException {
		// TODO 自动生成的方法存根
		return null;
	}

	public SeckillExecution executeSeckillProcedure(long seckillId,
			long userPhone, String md5) {
		// TODO 自动生成的方法存根
		return null;
	}
	private String getMD5(long seckillId){
		String base = seckillId + "/" + SLAT;
		String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
		LOG.info("___________________________md4:" + md5); 
		return md5;
	}
}
